package direct;

import cn.hutool.core.io.file.FileWriter;
import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;

public class ReceiveLogsDirect02 {

    private static final String EXCHANGE_NAME = "direct_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.208.134");
        factory.setUsername("admin");
        factory.setPassword("123");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        String queueName = channel.queueDeclare().getQueue();

        channel.queueBind(queueName, EXCHANGE_NAME, "error");
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            FileWriter fileWriter = new FileWriter("C:\\Users\\hz21076971\\Desktop\\myJava\\rabbitmq_error.txt");
            fileWriter.write(message, true);
            System.out.println(" [x] 错误日志成功写入文件...");
        };
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});
    }
}
